package com.gitee.wsl.net.ssdp.description

import com.gitee.wsl.net.ssdp.description.model.xml.SpecVersion
import io.ktor.client.engine.mock.*
import io.ktor.http.*
import kotlinx.coroutines.runBlocking
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull

class DescriptionServiceTest {

    @Test
    fun `successfully retrieves device description`() {
        runBlocking<Unit> {
            val testUrl = "http://192.168.178.1:49000/igddesc.xml"
            val stub = this::class.java.getResource("/stubs/RootDevice1Description.xml")?.readBytes()?:
                throw IllegalStateException("Stub with device description not found")
            val mockEngine = MockEngine { request ->
                if(request.url.toString() != testUrl) respond(
                    content = "NotFound",
                    status = HttpStatusCode.NotFound
                )

                respond(
                    content = stub,
                    status = HttpStatusCode.OK,
                    headers = headersOf(
                        HttpHeaders.ContentType to listOf("text/xml", "charset=\"utf-8\""),
                        HttpHeaders.ContentLanguage to listOf("en"),
                        HttpHeaders.ContentLength to listOf(stub.size.toString()),
                        HttpHeaders.Date to listOf("Wed, 21 Oct 2015 07:28:00 GMT")
                    )
                )
            }
            val testService = DescriptionService
            testService.setClientEngine(mockEngine)
            val descr = testService.getDeviceDescription(URLBuilder(testUrl).build())

            //asserts objects properties are as expected
            assertNotNull(descr)
            assertEquals(SpecVersion(1, 0), descr.specVersion)
            assertNull(descr.systemVersion)
            assertEquals("urn:schemas-upnp-org:device-1-0", descr.urn)
            assertNull(descr.configId)
            assertEquals("en", descr.language)

            assertNotNull(descr.device)

            assertEquals("urn:schemas-upnp-org:device:InternetGatewayDevice:1", descr.device.deviceType)
        }
    }
}